from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from .sers import *


class PageNum(PageNumberPagination):
    # 查询字符串中代表每页返回数据数量得参数名，默认值：None
    page_size_query_param = "max_page"
    # 查询字符串中代表页码得参数名，有默认值：page
    # page_query_param = 'page'
    # 一页中最多得结果条数
    page_size = 2


class ClassroomView(APIView):
    def get(self, request):
        class_obj = Classroom.objects.all().order_by('-id')
        # 分页
        paginator = PageNum()
        result_page = paginator.paginate_queryset(class_obj, request)
        ser_obj = ClassroomSer(result_page, many=True)
        return Response({"data": ser_obj.data})

    def post(self, request):
        data = request.data
        if data['address'] != "北京":
            return Response({"msg": "你的信息不是北京"})

        ser_obj = ClassroomSer(data=data)
        if ser_obj.is_valid():
            ser_obj.save()
            return Response(ser_obj.data)
        else:
            return Response(ser_obj.errors)

    def put(self, request):
        data = request.data
        instance = Classroom.objects.filter(class_name=data['class_name']).first()
        ser_obj = ClassroomSer(instance=instance, data=data)
        if ser_obj.is_valid():
            ser_obj.save()
            return Response(ser_obj.data)
        else:
            return Response(ser_obj.errors)


class UserView(APIView):

    def get(self, request):
        # 查询
        flag = request.query_params.get("flag")
        if flag == "1":
            user_obj = User.objects.all().order_by("age")
        elif flag == "2":
            user_obj = User.objects.all().order_by("-hight")
        elif flag == "3":
            user_obj = User.objects.filter(Q(hight__range=[150, 170]) | Q(age__lt=20))
        else:
            user_obj = User.objects.all()

        paginator = PageNum()
        result_page = paginator.paginate_queryset(user_obj, request)
        ser = UserSer(result_page, many=True)
        return paginator.get_paginated_response(ser.data)
